/*
 * Copyright 2022 Institute of Software Chinese Academy of Sciences, ISRC
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import router from '@system.router';
import featureAbility from '@ohos.ability.featureAbility';
import display from '@ohos.display';
import http from '@ohos.net.http';

const titles = [
    {
        'name': 'All'
    },
    {
        'name': 'Health'
    },
    {
        'name': 'Finance'
    },
    {
        'name': 'Technology'
    },
    {
        'name': 'Sport'
    },
    {
        'name': 'Internet'
    },
    {
        'name': 'Game'
    }
];
export default {
    props: {
        chatList: {
            default: []
        }
    },
    data: {
        //假数据
        titleList: titles,
        //        chatList: [],
        //置顶逻辑
        globalX: 0, //落点x轴
        globalY: 0, //落点y轴
        id: 0, //第几行数据

        //更新时间
        hours_minutes:'',
        msg: {
            type:'',
            touid:'',
            uid: ''
        },
        eventReturn: null,
        contentType:"",
    },

    onInit() {
        console.info('sessionList====onInit')
        this.chatList=this.$app.$def.chatData
        //绑定事件
        let refreshSessionList = () => {
            console.info('[eventBus]sessionList=====>eventBus refreshSessionList')
            this.chatList=this.$app.$def.chatData
        }
        let Bus = this.$app.$def.eventBus;
        this.eventReturn = Bus.$on('refreshSessionList',refreshSessionList)
        //绑定结束
        console.log('sessionList=====>display.width:' + display.width + "display.height：" + display.height);
        this.grantPermission();
        var obj = {uid:this.$app.$def.uid,touid:[],role:'ho_user',type:'login', content:'', stype:0}
        console.info('sessionList=====>obj:' + obj);
        this.$app.$def.mySocket.send(JSON.stringify(obj)); //预览时注释掉这一行
        console.info('sessionList=====>send uid:' + JSON.stringify(obj))
    },
    onShow(){
        console.info('sessionList====onShow')
    },
    onDestroy() {
        let Bus = this.$app.$def.eventBus;
        Bus.$off('refreshSessionList',this.eventReturn)
    },

    /*获取部分权限*/
    grantPermission() {
        console.info('sessionList=====>grantPermission')
        let context = featureAbility.getContext()
        context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
            console.info(`sessionList=====>requestPermissionsFromUser`);
        })
    },

    //转到 ”dialogPage“
    itemClick(idx){
        //传递点击的是第几行数据
        this.$app.$def.idx = idx;
        this.findMsgList(idx);
        router.push({
            uri: "pages/dialogPage/dialogPage",
        });

    },

    //打开弹出框
    onListClick(msg){
        this.globalX = msg.touches[0].globalX
        this.globalY = msg.touches[0].globalY
        this.$element("apiMenu").show({x: this.globalX,y:this.globalY});
    },

    //滑动屏幕进行置顶逻辑
    onMenuSelected(e){
        var id = this.id
        console.info("sessionList=====e.value : " + e.value);
        console.info("sessionList=====id : " + id);
        if(e.value == "top") {
            this.chatList.unshift(this.chatList[id])
            this.chatList.splice(++id, 1)
        } else if(e.value == "delete") {
            this.chatList.splice(id, 1);
        }
    },

    //当手机触碰屏幕取值
    onListFocus(chat,id){
        this.id = id
        this.date(chat)
        chat.readTime = this.hours_minutes
    },

    //”通讯录“ 列表
    message(){
        router.push({
            uri: "pages/mailList/mailList",
        });
    },

    //”发现“ 列表
    find(){
        router.push({
            uri: "pages/findList/findList",
        });
    },

    //“我的”列表
    my(){
        router.push({
            uri: "pages/myList/myList",
            params: {
                'uid': this.id,
            }
        });
    },

    //搜索逻辑——按姓名搜索
    search(index){
        /*let idnex = this.chatList.findIndex(function(){
        return this.chatList.title =='小李'
        })*/
    },

    //时间
    date(chat){
        var today = new Date();
        var hours = today.getHours() + ':'
        var minutes = today.getMinutes() + '.'
        var hours_minutes = hours + minutes
        this.hours_minutes = hours_minutes
    },
    //获取历史消息
    findMsgList(idx){
        console.log('sessionList=====findMsgList')
        let uid = this.$app.$def.uid;
        let toUid = this.$app.$def.chatData[idx].uid[0];
        let msgChoose = this.$app.$def.chatData[idx].unRead;
        let date = new Date(),
            year = date.getFullYear(), //获取完整的年份(4位)
            month = date.getMonth() + 1,//获取当前月份(0-11,0代表1月 //需要tosting转换
            strDate = date.getDate() // 获取当前日(1-31)
        let timestamp = year + "-" + month + "-" + strDate;
//        timestamp = "2022-09-28"
        console.log("sessionList====>get timestamp:  " + timestamp);
        console.info('sessionList====>get msgChoose: '+ msgChoose)
        //判断此处点击的为个人历史消息or群聊历史消息
        if(msgChoose == "say"){
            console.log("sessionList====>msgChoose == say");
            this.personMsg(uid,toUid,idx,timestamp);
        }else{
            console.log("sessionList====>msgChoose == group");
            this.groupMsg(uid,toUid,idx,timestamp);
        }
    },
    //个人历史消息获取
    personMsg(uid,toUid,idx,time){
        let httpRequest= http.createHttp();
        let promise = httpRequest.request("http://" + this.$app.$def.ip +"/message/getSingleChatMessages", {
            method: 'POST',
            extraData:JSON.stringify({"uid":uid, "toUid":toUid, "time":time}),
            connectTimeout: 60000,
            readTimeout: 60000,
            header: {
                'Content-Type': 'application/json'
            }
        });
        promise.then((value) => {
            let re = JSON.parse(value.result.toString());
            //log查看个人历史消息是否拿到？
            console.info('sessionList====>get personMsg re: '+JSON.stringify(re))
            console.info('sessionList====>get personMsg re.data: '+ JSON.stringify(re.data))
            //清空消息
            this.$app.$def.chatData[idx].MsgList = []
            for (let i = 0; i < re.data.length; i++) {
                let contentType;
                let contentValue = re.data[i].content;
                if(re.data[i].contentType == "0"){
                    contentType = 0;
                }else if(re.data[i].contentType == "1"){
                    contentType = 1;
                    contentValue = 'http://' + contentValue;
                }else if(re.data[i].contentType == "2"){
                    contentType = "file";
                    let contentFile = contentValue;
                    let fileName = contentFile.substring(contentFile.lastIndexOf("/") + 1);
                    let fileType = contentFile.substring(contentFile.lastIndexOf(".") + 1);
                    contentValue = {
                        fileUrl : 'http://' + contentFile,
                        fileName : fileName,
                        fileType : fileType,
                    }
                }else if(re.data[i].contentType == "3"){
                    contentType = "audio";
                    let content_audioSay = contentValue;
                    contentValue = {
                        path: 'http://' + content_audioSay,
                        dataTime:"语音消息，点击播放",
                        file: '',
                        date: '',
                        hasSend: true
                    };
                }else if(re.data[i].contentType == "4"){
                    contentType = 2;
                    contentValue = '/common/images/face/Expression_' + contentValue + '.png';
                }else {
                    contentType = 0;
                }
                //判断是否为本人发送消息
                if(re.data[i].sendUid == uid){
                    this.$app.$def.chatData[idx].MsgList.push({isMe: true,
                        sendUid:"",
                        messageType: contentType,
                        content: contentValue,
                        profPicUrl:'/common/images/bob.jpg',
                        createTime:re.data[i].createTime})
                }
                else if(re.data[i].sendUid == toUid){
                    this.$app.$def.chatData[idx].MsgList.push({isMe: false,
                        sendUid: re.data[i].sendUid,
                        messageType: contentType,
                        content: contentValue,
                        profPicUrl:'/common/images/bob.jpg',
                        createTime:re.data[i].createTime})
                }
            }
        }).catch((err) => {
            console.error(`sessionList====> errCode:${err.code}, errMessage1:${err.data}`);
        });
    },
    //群聊历史消息
    groupMsg(uid,toUid,idx,time){
        let httpRequest= http.createHttp();
        let promise = httpRequest.request("http://" + this.$app.$def.ip +"/message/getGroupMessages", {
            method: 'POST',
            extraData:JSON.stringify({"groupId":toUid,"time":time}),
            connectTimeout: 60000,
            readTimeout: 60000,
            header: {
                'Content-Type': 'application/json'
            }
        });
        promise.then((value) => {
            let re = JSON.parse(value.result.toString());
            //log查看群聊历史消息是否拿到？
            console.info('sessionList====>get groupMsg re: '+JSON.stringify(re));
            //清空消息
            this.$app.$def.chatData[idx].MsgList = []
            for (let i = 0; i < re.data.length; i++) {
                let contentType;
                let contentValue = re.data[i].content;
                if(re.data[i].contentType == "0"){
                    contentType = 0;
                }else if(re.data[i].contentType == "1"){
                    contentType = 1;
                    contentValue = 'http://' + contentValue;
                }else if(re.data[i].contentType == "2"){
                    contentType = "file";
                    let contentFile = contentValue;
                    let fileName = contentFile.substring(contentFile.lastIndexOf("/") + 1);
                    let fileType = contentFile.substring(contentFile.lastIndexOf(".") + 1);
                    contentValue = {
                        fileUrl : 'http://' + contentFile,
                        fileName : fileName,
                        fileType : fileType,
                    }
                }else if(re.data[i].contentType == "3"){
                    contentType = "audio";
                    let content_audioSay = contentValue;
                    contentValue = {
                        path: 'http://' + content_audioSay,
                        dataTime:"语音消息，点击播放",
                        file: '',
                        date: '',
                        hasSend: true
                    };
                }else if(re.data[i].contentType == "4"){
                    contentType = 2;
                    contentValue = '/common/images/face/Expression_' + contentValue + '.png';
                }else {
                    contentType = 0;
                }
                //判断是否为本人发送消息
                if(re.data[i].sendUid == uid){
                    this.$app.$def.chatData[idx].MsgList.push({isMe: true,
                        sendUid:"",
                        messageType: contentType,
                        content: contentValue,
                        profPicUrl:'/common/images/bob.jpg',
                        createTime:re.data[i].createTime})
                }
                else{
                    this.$app.$def.chatData[idx].MsgList.push({isMe: false,
                        sendUid: re.data[i].sendUid,
                        messageType: contentType,
                        content: contentValue,
                        profPicUrl:'/common/images/bob.jpg',
                        createTime:re.data[i].createTime})
                }
            }
        }).catch((err) => {
            console.error(`sessionList====> errCode:${err.code}, errMessage1:${err.data}`);
        });
    },

}



